package com.vcredit.creditcat.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.manager.CreditCatProcessManager;
import com.vcredit.creditcat.model.AuthItem;
import com.vcredit.creditcat.model.AuthLog;
import com.vcredit.creditcat.model.AuthTaobao;
import com.vcredit.creditcat.persistence.AuthTaobaoExtMapper;
import com.vcredit.creditcat.persistence.base.AuthTaobaoMapper;

/**
 * 
 **/
@Service
public class AuthTaobaoService {
	@Autowired
	private AuthTaobaoMapper mapper;
	@Autowired
	private AuthTaobaoExtMapper extMapper;
	@Autowired
	private CreditCatProcessManager creditCatProcessManager;
	@Autowired
	private AuthLogService authLogService;

	public void insert(AuthTaobao obj) {
		mapper.insert(obj);
	}

	public void update(AuthTaobao obj) {
		mapper.update(obj);
	}

	public List<AuthTaobao> findAll() {
		return mapper.findAll();
	}

	private List<AuthTaobao> find(AuthTaobao obj) {
		return mapper.find(obj);
	}

	public AuthTaobao findByProcessId(Long processId) {
		AuthTaobao param = new AuthTaobao();
		param.setProcessId(processId);
		List<AuthTaobao> list = find(param);
		if (!list.isEmpty())
			return list.get(0);
		return null;
	}

	public List<AuthTaobao> findUnCrawl() {
		return extMapper.findUnCrwal();
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updateCreditTaobao(AuthTaobao param) throws Exception {
		AuthTaobao authTaobao = findByProcessId(param.getProcessId());
		if (null != authTaobao) {
			param.setTaobaoProccessId(authTaobao.getTaobaoProccessId());
			update(param);
		} else {
			insert(param);
		}
		if (null != param.getIsReal() && param.getIsReal() == 1) {
			creditCatProcessManager.itemDone(new AuthItem(AuthItemEnum.TAOBAO.getCode()), authTaobao.getProcessId());
			authLogService.insert(new AuthLog(param.getProcessId(), param.getCust().getCustId(),
					AuthItemEnum.TAOBAO.getCode(), param.getExpiredTime(), new Date()));
		}
	}

	public void resetStatus(AuthTaobao param) {
		update(param);
	}
}